package com.asm.AshtonUtil;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class 发送JSON字符串6天翼云_APP请求2s心跳 {

    public static void main(String[] args) throws InterruptedException {

        final NioEventLoopGroup group = new NioEventLoopGroup();

        final Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
//                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));  //----- 日志 ------
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                super.channelRead(ctx, msg);
                                ByteBuf buffer = (ByteBuf) msg;
//                                log.debug("反馈消息（buffer）：" + buffer.toString());
                                log.debug("反馈消息（解码后 ）：" + buffer.toString(Charset.defaultCharset()));

                            }
                        });

                    }
                })
//                .connect("47.100.173.102", 6611).sync().channel();
                .connect("114.217.18.243", 6611).sync().channel();
//                .connect("localhost", 6611).sync().channel();
        // {"msgType":"appWeb","collectorId":"0010171617603800"}

        final String jsonMessage = "{\"msgType\":\"appWeb\",\"collectorId\":\"0010171617603800\"}";
        final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        final boolean[] isSending = {false};

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while(true){

                final String line = scanner.nextLine();
                if ("q".equals(line))
                {
                    channel.close();
                    break;
                } else if ("xl".equals(line)) {
                    if (!isSending[0]) {
                        // 启动定时任务，每隔 2 秒发送一次消息
                        scheduler.scheduleAtFixedRate(() -> {

                            log.debug("循环 发送消息：{}", jsonMessage);
                            channel.writeAndFlush(jsonMessage);

                        }, 0, 2, TimeUnit.SECONDS);
                        isSending[0] = true;
                    }
                } else if("once".equals(line)){
                    log.debug("发送消息：{}", jsonMessage);
                    channel.writeAndFlush(jsonMessage);
                }

                else {
                    log.debug("发送消息：{}", line);
                    channel.writeAndFlush(line);
                }

            }

        }).start();

        channel.closeFuture().addListener(future -> {
            // 关闭定时任务
            scheduler.shutdownNow();
            group.shutdownGracefully();
        });

    }


}

//{"msgType":"appWeb","collectorId":"0010171331829600"}